import React, { useState, useEffect } from 'react';
import { Card, Button, Row, Col, Statistic, Spin, Empty, message } from 'antd';
import { ShopOutlined, PlusOutlined } from '@ant-design/icons';
import { ProductCard } from '@/components';
import { productService } from '@/services';
import { Product, ProductQueryParams, ProductStatus } from '@/types/product';
import { useNavigate } from '@umijs/max';

const ProductList: React.FC = () => {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({
    total: 0,
    onSale: 0,
    todayAdded: 0,
    soldRate: 0
  });
  
  const navigate = useNavigate();

  useEffect(() => {
    loadProducts();
  }, []);

  const loadProducts = async () => {
    try {
      setLoading(true);
      const searchParams: ProductQueryParams = {
        page: 1,
        pageSize: 20
      };
      
      const result = await productService.getProducts(searchParams);
      setProducts(result.products || []);
      
      // 模拟统计信息
      setStats({
        total: result.products?.length || 0,
        onSale: result.products?.filter(p => p.status === ProductStatus.ACTIVE).length || 0,
        todayAdded: result.products?.filter(p => 
          new Date(p.publishedAt).toDateString() === new Date().toDateString()
        ).length || 0,
        soldRate: Math.round(((result.products?.filter(p => p.status === ProductStatus.SOLD).length || 0) / (result.products?.length || 1)) * 100)
      });
    } catch (error: any) {
      console.error('加载商品列表失败:', error);
      message.error(`加载商品列表失败: ${error.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  const handlePublishNew = () => {
    navigate('/products/publish');
  };

  const handleViewProduct = (product: Product) => {
    navigate(`/products/detail/${product.id}`);
  };

  const handleEditProduct = (product: Product) => {
    navigate(`/products/publish?edit=${product.id}`);
  };


  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      {/* 页面标题和统计信息 */}
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">商品管理</h1>
        <p className="text-gray-600">查看和管理所有商品信息</p>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} className="mb-6">
        <Col xs={24} sm={12} lg={6}>
          <Card className="shadow-sm border-0">
            <Statistic
              title="总商品数"
              value={stats.total}
              prefix={<ShopOutlined className="text-blue-500" />}
              valueStyle={{ color: '#0ea5e9' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card className="shadow-sm border-0">
            <Statistic
              title="在售商品"
              value={stats.onSale}
              prefix={<ShopOutlined className="text-green-500" />}
              valueStyle={{ color: '#22c55e' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card className="shadow-sm border-0">
            <Statistic
              title="今日新增"
              value={stats.todayAdded}
              prefix={<ShopOutlined className="text-blue-500" />}
              valueStyle={{ color: '#3b82f6' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card className="shadow-sm border-0">
            <Statistic
              title="成交率"
              value={stats.soldRate}
              precision={1}
              suffix="%"
              prefix={<ShopOutlined className="text-purple-500" />}
              valueStyle={{ color: '#8b5cf6' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 商品列表 */}
      <Card 
        className="shadow-sm border-0"
        title={
          <div className="flex justify-between items-center">
            <span className="text-lg font-semibold text-gray-900">商品列表</span>
            <div className="space-x-2">
              <Button type="primary" className="bg-blue-600 hover:bg-blue-700" onClick={handlePublishNew}>
                <PlusOutlined /> 发布新商品
              </Button>
            </div>
          </div>
        }
      >
        {loading ? (
          <div className="flex justify-center py-12">
            <Spin size="large" />
          </div>
        ) : products.length === 0 ? (
          <Empty 
            description="暂无商品数据" 
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            {products.map((product) => (
              <ProductCard
                key={product.id}
                product={product}
                showFavorite={true}
                showActions={true}
                onClick={() => handleViewProduct(product)}
                onEdit={() => handleEditProduct(product)}
                size="medium"
              />
            ))}
          </div>
        )}
      </Card>
    </div>
  );
};

export default ProductList;